<template>
  <!--迁移1添加一句注释，方便从新合并到test-->
  <el-container class="loginWrap">
    <el-main class="bg">
      <div class="login_right">
        <div class="login_back">
          <div class="head">
            <img :src="logo" alt="北汽新能源" />
          </div>
          <!-- 用户名登录页面 -->
          <div class="login-container" v-show="isShowuser">
            <el-form
              ref="loginForm1"
              :model="loginForm"
              :rules="loginRules"
              auto-complete="on"
              label-position="left"
              label-width="0px"
              class="card-box login-form"
            >
              <!-- <el-form-item prop="appId" class="el-form-item__white">
                  <span class="svg-container svg-container_login">
                    <svg-icon icon-class="home1" style="color:rgba(0,4,10,0.25)" />
                  </span>
                  <el-input
                    v-model="loginForm.appId"
                    onKeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
                    name="sitename"
                    type="text"
                    auto-complete="on"
                    placeholder="站点名称"
                  />
              </el-form-item>-->

              <el-form-item prop="username" class="el-form-item__white">
                <span class="svg-container svg-container_login">
                  <svg-icon icon-class="user" style="color:rgba(0,4,10,0.25)" />
                </span>
                <el-input
                  v-model.trim="loginForm.username"
                  onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
                  name="username"
                  type="text"
                  auto-complete="on"
                  placeholder="用户名"
                />
              </el-form-item>

              <el-form-item prop="password" class="el-form-item__white">
                <span class="svg-container">
                  <svg-icon icon-class="suo" style="color:rgba(0,4,10,0.25)" />
                </span>
                <el-input
                  :type="pwdType"
                  v-model.trim="loginForm.password"
                  onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
                  name="password"
                  auto-complete="on"
                  placeholder="密码"
                  @keyup.enter.native="doLogin('loginForm1')"
                />
                <span class="show-pwd" @click="showPwd">
                  <svg-icon
                    v-if="this.pwdType === 'password'"
                    icon-class="eye"
                    style="color:rgba(0,4,10,0.25)"
                  />
                  <svg-icon v-else icon-class="eyeShow" style="color:rgba(0,4,10,0.25)" />
                </span>
              </el-form-item>
              <!-- 验证码 -->
              <el-form-item
                v-if="isCodeImg"
                prop="verificationCode"
                class="el-form-item__white"
                style="display: flex;"
              >
                <span class="svg-container svg-container_login">
                  <svg-icon icon-class="user" style="color:rgba(0,4,10,0.25)" />
                </span>
                <el-input
                  v-model.trim="loginForm.verificationCode"
                  onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
                  name="verificationCode"
                  type="text"
                  auto-complete="on"
                  placeholder="验证码"
                />
                <img @click="doLogin('loginForm1')" class="verificationCode" :src="base64Img" />
              </el-form-item>
              <el-form-item class="login-button-wrapper">
                <el-button
                  :loading="loading"
                  type="primary"
                  class="login-button"
                  :disabled="isDisabled"
                  @click.native.prevent="doLogin('loginForm1')"
                >登&emsp;录</el-button>
              </el-form-item>
              <div style="height:20px; margin:17px 0px">
                <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
                  <el-checkbox
                    v-for="city in cities"
                    :label="city"
                    :key="city"
                  >{{city ==1?"记住密码":""}}</el-checkbox>
                </el-checkbox-group>
                <!-- <span
                  @click="appLogin"
                  style="float: right;"
                  v-if="loginForm.appId!==''"
                  class="remember-psd"
                >下载APP</span> -->
              </div>
            </el-form>
          </div>
        </div>
      </div>

      <!-- <el-footer class="foot">
        <foot />
      </el-footer>-->
    </el-main>
    <!-- 登陆拦截判断 -->
    <el-dialog :visible="isShowDialog" title="请先选择角色" width="60%" @close="handleClose" left>
      <div class="wrapScroll">
        <p
          style
          v-for="(item,index) of selectionRole"
          :key="index"
          @click="setUserRoleHandle(item)"
        >
          <router-link class="dialogP" to>
            <!-- to="./" -->
            公司：{{item.dealerName}}&nbsp;&nbsp;&nbsp;&nbsp;--
            部门：{{item.orgName}}&nbsp;&nbsp;&nbsp;&nbsp;--
            角色：{{item.roleName}}
          </router-link>
        </p>
      </div>
    </el-dialog>

    <!-- //绑定手机号 -->
    <el-dialog :visible="isBindPhone" title="绑定手机号" width="30%" @close="handleClose" left>
      <div class="login-container">
        <el-form
          ref="loginForm2"
          :model="loginPhoneForm"
          :rules="loginRules"
          auto-complete="on"
          label-position="left"
          label-width="0px"
          class="card-box login-form"
        >
          <el-form-item prop="getPhone" class="el-form-item__white">
            <span class="svg-container svg-container_login">
              <svg-icon icon-class="user" style="color:rgba(0,4,10,0.25)" />
            </span>
            <el-input
              v-model="loginPhoneForm.getPhone"
              name="getPhone"
              type="text"
              auto-complete="on"
              placeholder="输入手机号"
            />

            <el-button class="get_code" @click="getCode('isBindPhone')">获取验证码</el-button>
          </el-form-item>
          <el-form-item prop="getCheckCode" class="el-form-item__white">
            <span class="svg-container">
              <svg-icon icon-class="safe" style="color:rgba(0,4,10,0.15);width:20px" />
            </span>
            <el-input
              v-model.trim="loginPhoneForm.getCheckCode"
              onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false;"
              type="text"
              maxlength="6"
              name="getCheckCode"
              auto-complete="on"
              placeholder="输入验证码"
              @keyup.enter.native="doLogin('isBindPhone')"
            />
          </el-form-item>
          <p v-show="!show" style="padding:20px 0;">验证码倒计时：{{count}}s</p>
          <el-form-item class="login-button-wrapper">
            <el-button
              :loading="loading"
              type="primary"
              class="login-button"
              :disabled="isShowNext"
              @click.native.prevent="doLogin('isBindPhone')"
            >确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <!-- app下载弹框 -->
    <el-dialog title="请扫描二维码下载APP" :visible.sync="appIsShow" width="300px" center>
      <qrCodeApp :qrcodeUrl="qrcodeUrl" />
    </el-dialog>
  </el-container>
</template>

<script>
import { mapActions, mapState } from 'vuex';
import * as types from '@/api/login/types';
import { sleep } from '@/utils';
import { setToken, setDataType, setAppId, jsEncrypt, setUserOrgId } from '@/assets/js/auth';
import { queryDataByAppType } from '@/api/login/index';
import qrCodeApp from './qrCodeApp/index';
import {
  doLogin,
  initLogin,
  getUserInfo,
  sendPhoneCode,
  roleDetail,
  setUserRole,
  weChatLogin,
  getVerificationCode,
  postBindingPhone,
  getSendSms,
  forgetUpdatePassword,
  afterSale
} from '@/api/login/index';
import { getUserPermissionCtrl } from '@/api/index';
// import wxlogin from ' vue-wxlogin1';
/*迁移*/
import _ from 'lodash';
import foot from './foot';
import pc_cyx from '@/assets/img/logo2.png';
import { setTimeout, clearTimeout } from 'timers';
// import { initUserData } from '@/api/login';
import { getToken } from '@/utils/auth';
import Cookies from 'js-cookie';
export default {
  name: 'Login',
  components: {
    foot,
    qrCodeApp
    // wxlogin
  },
  /* beforeRouteLeave (to, from, next) {
    // alert(to,"to")
    if(to.query.code){
      getAccessToken(to.query.code).then(res=>{
        // alert(res)
      })
    } else {
      next()
    }
  }, */
  data() {
    const validateAppId = (rule, value, callback) => {
      if (_.isEmpty(value)) {
        callback(new Error('请输入正确的站点名称'));
      } else {
        callback();
      }
    };
    const validateUsername = (rule, value, callback) => {
      if (_.isEmpty(value)) {
        callback(new Error('请输入正确的用户名'));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      var g = /^(?!\d+$)(?![a-zA-Z]+$)(?![^(a-zA-Z|\d|\u4E00-\u9FA5)]+$).{6,32}$/;
      if (!g.test(value)) {
        callback(new Error('长度至少6位;数字,字母,特殊字符至少包含两种!'));
      } else {
        callback();
        this.loginForm3IsShow = false;
      }
      /* if (_.isEmpty(value)) {
        callback(new Error('密码不能为空'));
      } else {
        callback();
      } */
    };
    const validatePhone = (rule, value, callback) => {
      if (_.isEmpty(value)) {
        callback(new Error('请输入正确的手机号'));
      } else {
        callback();
      }
    };
    const validateVerifyCode = (rule, value, callback) => {
      if (_.isEmpty(value)) {
        callback(new Error('请输入验证码'));
      } else {
        callback();
      }
    };
    return {
      // form: {
      //   username: '',
      //   password: ''
      // },
      // rules: {
      //   username: [{ required: true, message: '请输入用户名.', trigger: 'blur' }],
      //   password: [{ required: true, message: '请输入密码.', trigger: 'blur' }, { min: 6, max: 18, message: '长度在 3 到 6 个字符', trigger: 'blur' }]
      // },

      /*迁移*/
      // appid: 'wx745b0506045eeda2',
      // scope: 'snsapi_login',
      // state: Math.random()*10000,
      // // style: 'black',
      // redirect_uri: `https://kfcyx.yycsy.com/getAccessToken`,
      // 20191023-e
      show: true,
      count: '',
      isBindPhone: false,
      loginForm3IsShow: true,
      isShowNext: true,
      ForgetPsd: true,
      isDisabled: false,
      isCodeImg: false,
      codeImg: '',
      activeName: 'first', //默认第一个
      stepsName: 'first',
      isShowuser: true,
      isShowWechat: true,
      isShowPsd: false, //忘记密码页面
      isShowReturn: false, //返回登录
      wechatPicShow: false, //微信二维码弹框
      wechatPicUrl: '',
      isShowDialog: false,
      selectionRole: [],
      checks: false,
      cities: [1],
      checkedCities: [],
      loginForm: {
        appId: 'RL',
        username: '',
        password: '',
        resetPsw1: '', //重置密码
        resetPsw2: '', //重置密码
        codeShow: false,
        // count: '获取验证码'
        getPhone: '',
        getCheckCode: ''
      },
      loginPhoneForm: {
        appId: 'RL',
        phone: '', //手机号
        checkCode: '', //验证码
        codeShow: false,
        // count: '获取验证码',
        loginType: 2,
        getPhone: '',
        getCheckCode: ''
      },
      qrcodeUrl: '',
      appIsShow: false,
      base64Img: '',
      url: `${window.location.origin}/cyx_pc_manager/index.html#/setLogin`,
      // url:`https://cscyx.yycsy.com/cyx_pc_manager/index.html#/setLogin`,
      loginRules: {
        appId: [{ required: true, trigger: 'blur', validator: validateAppId }],
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePass }],
        resetPsw1: [{ required: true, trigger: 'blur', validator: validatePass }],
        resetPsw2: [{ required: true, trigger: 'blur', validator: validatePass }],
        phone: [
          { required: true, trigger: 'blur', validator: validatePhone },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码有误', trigger: 'blur' }
        ],
        checkCode: [{ required: true, trigger: 'blur', validator: validateVerifyCode }],
        getPhone: [
          { required: true, trigger: 'blur', validator: validatePhone },
          { min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          { pattern: /^1[3456789]\d{9}$/, message: '手机号码有误', trigger: 'blur' }
        ],
        getCheckCode: [{ required: true, trigger: 'blur', validator: validateVerifyCode }]
      },
      loading: false,
      pwdType: 'password',
      height: document.body.clientHeight - 120,
      logo: pc_cyx,
      timer: null,
      isLogin: false //是否已经点击登录按钮
    };
  },
  computed: {
    ...mapState('app', ['btnLoading']),
    loginBtnState() {
      return this.btnLoading[types.LOGIN];
    }
  },

  mounted() {
    this.init();
    //迁移
    //  log('环境:', process.env.NODE_ENV)
    //  log('地址:', process.env.BASE_API)
  },
  methods: {
    ...mapActions('app', ['createLoginInfo']),
    init() {
      this.isLogin = false;
      let allCookie = document.cookie.split(';');

      allCookie.forEach(x => {
        if (x.indexOf('CheckedCitiesData') > -1) {
          if (x.split('=')[1] == 2) {
            this.checkedCities = [];
          } else {
            this.checkedCities.push(Number(x.split('=')[1]));
          }
        }
        if (x.indexOf('CheckedAppId') > -1) {
          this.loginForm.appId = x.split('=')[1];
        }
        if (x.indexOf('CheckedUsername') > -1) {
          this.loginForm.username = x.split('=')[1];
        }
        if (x.indexOf('CheckedPassword') > -1) {
          this.loginForm.password = x.split('=')[1];
        }
      });
      console.log(this.checkedCities, this.loginForm.appId, this.loginForm.username, this.loginForm.password, 'this.checkedCities');
      if (this.checkedCities[0] != 1) {
        Cookies.set('CheckedAppId', '');
        Cookies.set('CheckedUsername', '');
        Cookies.set('CheckedPassword', '');
        this.loginForm.appId = 'RL';
        this.loginForm.username = '';
        this.loginForm.password = '';
      }
    },

    //记住密码
    handleCheckedCitiesChange(value) {
      console.log(value, '456');

      Cookies.set('CheckedAppId', this.loginForm.appId);
      Cookies.set('CheckedUsername', this.loginForm.username);
      Cookies.set('CheckedPassword', this.loginForm.password);
      Cookies.set('CheckedCitiesData', value[0] == 1 ? 1 : 2);
    },
    //app下载
    async appLogin() {
      var url = window.location.href;
      var domain = url.split('/');
      this.qrcodeUrl = domain[0] + '//' + domain[2] + '/wxVersion';
      this.appIsShow = true;
    },
    /*修改登录*/
    async doLogin(loginForm) {
      localStorage.setItem('appId', this.loginForm.appId);
      console.log(loginForm);
      // 判断是否是验证码登录
      if (loginForm.loginType == 2) {
        this.checks = true;
      } else if (loginForm == 'loginForm2') {
        this.ForgetPsd = false;
      } else if (loginForm == 'loginForm3') {
        if (this.loginForm.resetPsw1 != this.loginForm.resetPsw2) {
          this.$message.info('两次密码不一致');
        } else {
          let params = {
            newPassword: jsEncrypt(this.loginForm.resetPsw1),
            checkCode: this.loginForm.getCheckCode,
            phone: this.loginForm.getPhone,
            appId: this.loginForm.appId ? this.loginForm.appId : 'RL'
          };
          forgetUpdatePassword(params).then(res => {
            console.log(res, '忘记密码，重置密码');
            if (res.resultCode == 200) {
              this.loginForm.resetPsw1 = '';
              this.loginForm.resetPsw2 = '';
              this.ForgetPsd = true;
              this.isShowuser = true;
              this.isShowWechat = true;
              this.isShowPsd = false;
              this.isShowReturn = false;
            }
          });
        }
      } else if (loginForm == 'isBindPhone') {
        this.checks = false;
        //绑定手机号
        let postBindingPhoneData = {
          checkCode: this.loginPhoneForm.getCheckCode,
          phone: this.loginPhoneForm.getPhone,
          appId: this.loginForm.appId,
          username: this.loginForm.username,
          confirm: 0
        };
        postBindingPhone(postBindingPhoneData).then(res => {
          if (res.resultCode == 200) {
            this.$message.success(`手机号绑定成功`);
            this.isBindPhone = false;
            this.$router.push('/');
            // this.checks = true;
          } else if (res.resultCode == 995) {
            console.log('手机号绑定过多');
            this.checks = false;
            this.open2();
          } else {
            console.log('手机号errMsg');
            this.$message.warning(`${res.errMsg}`);
          }
        });
      } else {
        // 正常登录
        this.$refs[loginForm].validate(valid => {
          if (valid) {
            this.checks = true;
          } else {
            // console.log('error submit!!');
            this.$message.warning('登录失败');
            return false;
          }
        });
      }
      if (this.checks) {
        //判断是否是在线状态
        Cookies.set('isOnline', 1);
        localStorage.setItem('isOnline', 1);
        this.isDisabled = true;
        let res = '';
        if (loginForm.loginType == 2) {
          res = await doLogin({ ...loginForm });
        } else {
          if (this.loginForm.verificationCode) {
            res = await doLogin({
              appId: this.loginForm.appId,
              username: this.loginForm.username,
              password: jsEncrypt(this.loginForm.password),
              verificationCode: this.loginForm.verificationCode
            });
          } else {
            res = await doLogin({
              appId: this.loginForm.appId,
              username: this.loginForm.username,
              password: jsEncrypt(this.loginForm.password)
            });
          }
        }

        console.log(res, 'res');
        if (res.resultCode === 200) {
          setToken(res.data.jwt);
          // setDataType(res.data.rData.dataType);
          setDataType(res.data.dataType);
          if (this.checkedCities[0] != 1) {
            Cookies.set('CheckedAppId', '');
            Cookies.set('CheckedUsername', '');
            Cookies.set('CheckedPassword', '');
            this.loginForm.appId = 'RL';
            this.loginForm.username = '';
            this.loginForm.password = '';
          } else {
            Cookies.set('CheckedAppId', this.loginForm.appId);
            Cookies.set('CheckedUsername', this.loginForm.username);
            Cookies.set('CheckedPassword', this.loginForm.password);
          }
          // 登陆成功后判断角色
          // if(this.isShowDialog){
          this.selectionRole = [];
          roleDetail()
            .then(res => {
              this.isDisabled = false;
              res.data.forEach(x => {
                this.selectionRole.push(x);
              });
              console.log(this.selectionRole.length, 'selectionRole');
              if (this.selectionRole.length == 1) {
                console.log(123, this.selectionRole[0], 'this.selectionRole');
                this.isShowDialog = false;
                this.setUserRoleHandle(this.selectionRole[0]);
              } else {
                this.isShowDialog = true;
              }
            })
            .catch(err => {
              this.isDisabled = false;
            });
          // }
        } else if (res.resultCode === 998) {
          if (res.errMsg) {
            this.isDisabled = false;
            this.base64Img = `data:image/png;base64,${
              (res.errMsg || '')
                .split(',')[1]
                .split(':')[1]
                .split('"')[1]
            }`;
            this.isCodeImg = true;
            console.log(this.base64Img, 'this.base64Img');
          }
        } else if (res.resultCode === 997) {
          clearTimeout(this.timer); //清除延迟执行
          this.timer = setTimeout(() => {
            //设置延迟执行
            this.isDisabled = false;
          }, 3000);
        } else if (res.resultCode === 996) {
          this.isDisabled = false;
          this.open();
        } else if (res.resultCode == 500) {
          this.isDisabled = false;
        } else {
          this.isDisabled = false;
        }
      } else {
        this.isDisabled = false;
      }
    },
    // 绑定手机号
    open() {
      console.log('open');
      this.$confirm('可用绑定的手机号登录APP,找回密码', '您还未绑定手机号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.isBindPhone = true;
          /* this.$message({
            type: 'success',
            message: '删除成功!'
          }); */
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    //手机号已绑定是否继续绑定
    open2() {
      this.$confirm('手机号已绑定其他账号，如继续绑定，则将于原账号进行解绑', '提示', {
        confirmButtonText: '继续绑定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.isBindPhone = false;
          let postBindingPhoneData = {
            phone: this.loginPhoneForm.getPhone,
            appId: this.loginForm.appId,
            username: this.loginForm.username,
            confirm: 1
          };
          postBindingPhone(postBindingPhoneData).then(res => {
            console.log(res, '是否继续绑定');
          });
          /* this.$message({
            type: 'success',
            message: '删除成功!'
          }); */
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    //保存角色
    async setUserRoleHandle(data) {
      await setUserOrgId(data.userOrgId);
      if (this.isShowDialog) {
        this.isLogin = true;
        this.isDisabled = true;
      }
      await getUserPermissionCtrl().then(res => {
        if (JSON.stringify(res.data) !== '{}') {
          Object.keys(res.data).forEach(x => {
            console.log(res.data[`${x}`], 'x');
            localStorage.setItem(`${x}`, res.data[`${x}`]);
          });
        }
      });
      afterSale().then(res => {
        console.log(res, 'res123');
        Cookies.set('afterSale', res.data);
      });

      Cookies.set('roleType', data.roleType);
      localStorage.setItem('roleType', data.roleType);
      setUserRole(data).then(res => {
        if (res.resultCode == 200) {
          this.initUserInfo();
        }
      });
    },
    async initUserInfo() {
      await initLogin();
      const {
        data: { userInfo }
      } = await getUserInfo();
      this.createLoginInfo({
        id: userInfo.userId,
        name: userInfo.userName,
        employeeNo: userInfo.employeeNo,
        companyId: userInfo.companyId,
        ownerCode: userInfo.ownerCode
      });
      const userAppId = await getUserInfo();
      if (userAppId.resultCode == 200) {
        setAppId(userAppId.data.userInfo.appId);
        Cookies.set('appId', userAppId.data.userInfo.appId);
        localStorage.setItem('appId', userAppId.data.userInfo.appId);
      }
      await sleep(100);
      this.$router.push({ path: '/' });
    },
    // 关闭
    handleClose() {
      this.isShowDialog = false;
      this.isBindPhone = false;
      this.checks = false;
      if (!this.isLogin) {
        setToken();
        setDataType();
        this.isDisabled = false;
      } else {
        this.isDisabled = true;
      }
      sleep(0);
    },
    /*迁移*/
    showPwd() {
      if (this.pwdType === 'password') {
        this.pwdType = '';
      } else {
        this.pwdType = 'password';
      }
    },
    // 返回用户名登录
    returnClick() {
      this.isShowuser = true;
      this.isShowWechat = true;
      this.isShowPsd = false;
      this.isShowReturn = false;
    },
    // 忘记密码
    forgetPsd() {
      this.isShowuser = false;
      this.isShowPsd = true;
      this.isShowWechat = false;
      this.isShowReturn = true;
    },

    // 微信登录form
    weChatPicLogin() {
      this.wechatPicShow = true;
      weChatLogin().then(res => {
        console.log(res);
        // this.wechatPic = 'data:image/jpeg;base64,'+res.data.url;
        this.wechatPicUrl = res.data.url;
      });
    },

    // 切换登录选项
    handleClick(tab, event) {
      console.log(tab, event);
      this.$refs.loginPhoneForm.resetFields();
      this.$refs.loginForm1.resetFields();
      this.$refs.loginForm2.resetFields();
      this.$refs.loginForm3.resetFields();
    },

    // 忘记密码步骤
    stepsClick(tab, event) {
      console.log('修改密码', tab);
    },
    // 获取验证码
    async getCode(loginForm) {
      let params = {
        phone: this.loginPhoneForm.phone,
        appId: this.loginPhoneForm.appId ? this.loginPhoneForm.appId : 'RL'
      };
      // console.log(loginForm,"验证码登陆",this.loginPhoneForm.phone);
      // codeLogin验证码登陆
      if (loginForm == 'codeLogin') {
        if (!this.loginPhoneForm.phone) {
          // this.$message.info('手机号码不能为空');
          return false;
        } else {
          console.log('验证码登录');
          if (this.show) {
            getVerificationCode(params)
              .then(res => {
                if (res.resultCode == 200) {
                  this.$message.success('验证码发送成功');
                  console.log('验证码登录', res);
                  const TIME_COUNT = 60;
                  if (!this.timer) {
                    this.count = TIME_COUNT;
                    this.show = false;
                    this.timer = setInterval(() => {
                      if (this.count > 0 && this.count <= TIME_COUNT) {
                        this.count--;
                      } else {
                        this.show = true;
                        // Cookies.set('verificationCode', '');
                        clearInterval(this.timer);
                        this.timer = null;
                      }
                    }, 1000);
                  }
                }

                /* if(res.resultCode != 200){
                    this.$message.info(`${res.errMsg}`);
                  } */
              })
              .catch(err => {
                this.show = true;
              });
          }
        }
      } else if (loginForm == 'getCode') {
        // console.log('getCode',this.loginForm)
        //忘记密码，获取验证码
        if (!this.loginForm.getPhone) {
          // this.$message.info('手机号码不能为空');
          return false;
        } else {
          getSendSms(this.loginForm.getPhone).then(res => {
            this.$message.success('验证码发送成功');
            console.log(res, '忘记密码');
            if (res.resultCode == 200) {
              this.isShowNext = false;
            }
          });
        }
      } else if (loginForm == 'isBindPhone') {
        this.isShowNext = false;
        params.bindingPhone = 1;
        params.phone = this.loginPhoneForm.getPhone;
        params.checkCode = this.loginPhoneForm.getCheckCode;
        console.log(this.loginPhoneForm, '绑定手机号params', params);
        if (this.show) {
          getVerificationCode(params).then(res => {
            this.$message.success('验证码发送成功');
            console.log('绑定手机号res', res);
            let TIME_COUNT = 60;
            if (!this.timer) {
              this.count = TIME_COUNT;
              this.show = false;
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--;
                } else {
                  this.show = true;
                  // Cookies.set('verificationCode', '');
                  clearInterval(this.timer);
                  this.timer = null;
                }
              }, 1000);
            }
            /* if(res.resultCode != 200){
                  this.$message.info(`${res.errMsg}`);
                } */
          });
        }
      }
    },

    // 用户名登录
    handleLogin(loginForm) {
      this.$refs[loginForm].validate(valid => {
        if (valid) {
          this.loading = true;
          // debugger
          // this.$store.dispatch('Login', this.loginForm
          this.$store
            .dispatch('Login', {
              appId: this.loginForm.appId,
              username: this.loginForm.username,
              password: this.$jsEncrypt(this.loginForm.password)
            })
            .then(res => {
              initUserData()
                .then(res => {
                  console.log('登录用户', res);
                  this.loading = false;
                  const path = this.$route.query.redirect ? this.$route.query.redirect : '/';
                  this.$router.push({ path: path });
                  localStorage.setItem('codeId', res.dataType);
                  Cookies.set('codeId', res.dataType);
                  this.logins();
                })
                .catch(() => {
                  this.loading = false;
                });
            })
            .catch(() => {
              this.loading = false;
            });
        } else {
          console.log('error submit!!');
          this.$message.warning('登录失败');
          return false;
        }
      });
    },
    // 验证码登录
    codeLogin() {
      let codeLoginParams = {
        phone: this.loginPhoneForm.phone,
        appId: localStorage.getItem('appId') ? localStorage.getItem('appId') : 'RL',
        checkCode: this.loginPhoneForm.checkCode,
        loginType: 2
      };
      console.log('验证码登陆', codeLoginParams);
      this.doLogin(codeLoginParams);
    },
    // 微信登录
    weixinLogin() {},
    //主系统接入
    logins() {
      var data = {
        code: 200,
        appId: this.loginForm.appId,
        jwt: getToken()
      };
      document.getElementById('test_iframe').contentWindow.postMessage(data, `${window.location.origin}/cyx_pc_manager/index.html#/`);
      // document.getElementById("test_iframe").contentWindow.postMessage(data,`http://cscyx.yycsy.com/cyx_pc_manager/index.html#/`)
    }
  }
};
</script>

<style lang="less" scoped>
/*迁移样式*/
/*$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;
$black: #000;*/

@bg: #2d3a4b;
@dark_gray: #889aa4;
@light_gray: #eee;
@black: #000;
.loginWrap {
  .head {
    position: relative;
    text-align: center;
  }
  .head img {
    width: 70%;
    margin: 0px auto 120px auto;
  }
  .foot {
    position: fixed;
    bottom: 0;
    left: 0px;
    font-family: 'SimSun';
    font-size: 12px;
    display: block;
    min-width: 620px;
    width: calc(100% - 580px);
    text-align: center;
    color: #fff;
  }
  .el-main {
    padding: 0px;
  }
  .bg {
    min-width: 1200px;
    z-index: 95;
    position: absolute;
    width: 100%;
    height: 100%;
    background: url('../../assets/img/login1.jpg') no-repeat center center;
    background-size: cover;
  }
  .login_layout {
    width: 800px;
    height: 440px;
    margin: 70px auto;
    background-color: #fff;
    box-shadow: 0 0 10px 0 rgb(236, 243, 252);
  }

  .login_left {
    float: left;
    width: 320px;
    height: 100%;
    // background-color: #fff;
    background: url('../../assets/img/login.png') no-repeat left;
    background-size: 100%;
  }

  .login_right {
    float: right;
    width: 30%;
    min-width: 400px;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: center; /* 水平居中 */
    // align-items: center; /* 垂直居中 */
  }
  .el-checkbox-group {
    display: inline;
  }
  .remember-psd {
    float: right;
    cursor: pointer;
    margin-bottom: 10px;
    font-size: 14px;
    color: @primaryColor;
    font-family: PingFangSC-Regular;
    .el-checkbox__input.is-checked + .el-checkbox__label {
      color: @primaryColor;
    }
  }

  .login-button-wrapper {
    border: none !important;
    text-align: center;
    margin-top: 20px;
    .login-button {
      width: 100%;
      border: none;
      font-weight: bold;
      background: @primaryColor;
      color: #fff;
      font-size: 16px;
      padding: 12px 0px;
      border-radius: 5px;
    }
  }

  .login-container {
    width: 100%;
    input {
      background: #000;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      // color: #fff;
    }
    input:-webkit-autofill {
      box-shadow: 0 0 0px 1000px white inset !important;
    }
    .el-input {
      display: inline-block;
      color: #fff;
      background: none;
      height: 40px;
      line-height: 40px;
      border-radius: 5px;
    }
    .el-form-item__white {
      background: none;
      position: relative;
    }

    .get_code {
      position: absolute;
      top: 7px;
      right: 3px;
      outline: none;
      background-color: transparent;
      border: none;
      font-size: 13px;
      // width: 102px;
      // height: 22px;
      // line-height: 22px;
      // font-family: PingFangSC-Regular;
      color: rgba(0, 4, 10, 0.3);
      // cursor: pointer;
      // border-left: 1px solid rgba(0, 4, 10, 0.15);
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;
    }
    .svg-container {
      padding: 6px 5px 6px 15px;
      color: #fff;
      vertical-align: middle;
      width: 10px;
      display: none;
      &_login {
        font-size: 20px;
      }
    }
    .title {
      font-size: 26px;
      font-weight: 400;
      color: @light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
    .login-form {
      position: relative;
      left: 0;
      top: 4%;
      width: 300px;
      padding: 5px;
      margin: 0 auto;
      // background: rgba(0, 0, 0, 0.4);
      // border-radius: 20px;
    }
    .el-form-item {
      height: 50px;
      border-radius: 4px;
      color: #454545;
      // background: rgba(0, 0, 0, 0.1);
    }
    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: @dark_gray;
      cursor: pointer;
      user-select: none;
    }
    .thirdparty-button {
      position: absolute;
      right: 35px;
      bottom: 28px;
    }
  }
  .el-form .el-form-item /deep/ .el-form-item__error {
    left: 16px;
    padding-top: 5px;
  }

  .WeChat {
    /*cursor: pointer;*/
    text-align: center;
  }
  .weixin_login {
    // text-align: center;
    font-size: 12px !important;
    color: rgba(0, 4, 10, 0.45);
    margin-top: 5px;
    cursor: pointer;
  }
  .wx_icon {
    cursor: pointer;
  }

  .forget-psd {
    margin-top: 105px;
  }

  .return {
    cursor: pointer;
    position: absolute;
    top: 60px;
    right: 70px;
    font-size: 14px;
    color: rgba(24, 144, 255, 1);
  }

  .el-tabs__header {
    margin: 40px 140px 20px;
  }
  .wrapScroll {
    max-height: 300px;
    overflow-y: scroll;
  }
  .dialogP {
    font-size: 17px;
    line-height: 50px;
    padding-left: 10px;
    display: inline-block;
  }
  .dialogP:hover {
    background: #5fb2f9;
  }
  // 2021-4-17 11:55:33 qjh 验证码适当放大
  .verificationCode {
    // width: 30%;
    width: 45%;
    // float: left;
    float: right;
    margin: -35px 6px 0 0;
    position: relative;
    z-index: 99;
    cursor: pointer;
  }
  .ForgetPsd {
    text-align: center;
    line-height: 40px;
    span {
      display: inline-block;
      margin-right: 20px;
    }
    .color4395ff {
      color: #4395ff;
    }
    span:nth-child(3) {
      margin-right: 0;
    }
  }
}

.el-input--small /deep/ .el-input__inner {
  display: inline-block;
  color: #000;
  background: rgba(255, 255, 255, 0.3);
  height: 40px;
  border-radius: 5px;
  line-height: 40px;
}
</style>
